package com.bw.kf.playvideo

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.SingleEvent
import kotlinx.coroutines.launch
import com.example.common.mvi.NetworkResult

/**
 * 播放视频页面的ViewModel
 */
class PlayVideoViewModel : BaseViewModel<PlayVideoIntent, PlayVideoViewState, PlayVideoResult>() {
    
    // 创建CommentRepository实例
    private val repository: CommentRepository = CommentRepository()
    
    override fun initialState(): PlayVideoViewState = PlayVideoViewState()
    
    override suspend fun handleIntent(intent: PlayVideoIntent) {
        when (intent) {
            is PlayVideoIntent.InitializePlayer -> initializePlayer()
            is PlayVideoIntent.PlayVideo -> playVideo()
            is PlayVideoIntent.PauseVideo -> pauseVideo()
            is PlayVideoIntent.SeekTo -> seekTo(intent.position)
            is PlayVideoIntent.ToggleLike -> toggleLike()
            is PlayVideoIntent.ToggleCollect -> toggleCollect()
            is PlayVideoIntent.ShowComments -> showComments(intent.datatype, intent.itemid)
            is PlayVideoIntent.SendComment -> sendComment(intent.datatype, intent.itemid, intent.content)
            is PlayVideoIntent.SendReply -> sendReply(intent.datatype, intent.itemid, intent.content, intent.parentId, intent.replyToUserId, intent.replyToUserName)
            is PlayVideoIntent.LikeComment -> likeComment(intent.commentId)
            is PlayVideoIntent.ShowReward -> showReward()
        }
    }
    
    fun setVideoData(videoData: HomeData) {
        updateState(currentState().copy(videoData = videoData))
    }
    
    private fun initializePlayer() {
        viewModelScope.launch {
            updateState(currentState().copy(isLoading = true))
            // 这里可以添加播放器初始化逻辑
            updateState(currentState().copy(isLoading = false))
        }
    }
    
    private fun playVideo() {
        updateState(currentState().copy(isPlaying = true))
    }
    
    private fun pauseVideo() {
        updateState(currentState().copy(isPlaying = false))
    }
    
    private fun seekTo(position: Long) {
        updateState(currentState().copy(currentPosition = position))
    }
    
    private fun toggleLike() {
        val newLikeState = !currentState().isLiked
        updateState(currentState().copy(isLiked = newLikeState))
        sendEvent(SingleEvent.ShowToast(if (newLikeState) "已点赞" else "取消点赞"))
    }
    
    private fun toggleCollect() {
        val newCollectState = !currentState().isCollected
        updateState(currentState().copy(isCollected = newCollectState))
        sendEvent(SingleEvent.ShowToast(if (newCollectState) "已收藏" else "取消收藏"))
    }
    
    private suspend fun showComments(datatype: Int, itemid: String) {
        sendEvent(SingleEvent.ShowToast("开始加载评论列表"))

        // 更新评论加载状态
        updateState(currentState().copy(isCommentsLoading = true))
        
        // 调用repository的getComments方法并收集结果
        repository.getComments(datatype, itemid).collect { result ->
            when (result) {
                is NetworkResult.Loading -> {
                    // 已经设置了加载状态，这里不需要额外处理
                }
                is NetworkResult.Success -> {
                    // 使用CommentUtils进行时间排序
                    val sortedComments = CommentUtils.sortComments(
                        result.data.data, 
                        CommentSortType.TIME_DESC
                    )
                    
                    // 评论加载成功，更新评论列表
                    updateState(currentState().copy(
                        isCommentsLoading = false,
                        comments = sortedComments
                    ))
                    sendEvent(SingleEvent.ShowToast("评论加载成功，共${sortedComments.size}条评论"))
                }
                is NetworkResult.Error -> {
                    updateState(currentState().copy(
                        isCommentsLoading = false,
                        error = result.exception.message ?: "加载评论失败"
                    ))
                    sendEvent(SingleEvent.ShowToast("加载评论失败: ${result.exception.message}"))
                }
            }
        }
    }
    
    private suspend fun sendComment(datatype: Int, itemid: String, content: String) {
        updateState(currentState().copy(isSendingComment = true))
        
        // 直接调用repository的sendComment方法，不再创建SendCommentRequest对象
        repository.sendComment(datatype, itemid, content).collect { result ->
            when (result) {
                is NetworkResult.Loading -> {
                    // 已经设置了发送状态，这里不需要额外处理
                }
                is NetworkResult.Success -> {
                    // 评论发送成功
                    updateState(currentState().copy(isSendingComment = false))
                    sendEvent(SingleEvent.ShowToast(result.data.msg))
                    
                    // 添加新评论到列表
                    result.data.data?.let { addNewComment(it) }
                }
                is NetworkResult.Error -> {
                    updateState(currentState().copy(
                        isSendingComment = false,
                        error = result.exception.message ?: "评论发送失败"
                    ))
                    sendEvent(SingleEvent.ShowToast("评论发送失败: ${result.exception.message}"))
                }
            }
        }
    }
    
    private suspend fun sendReply(datatype: Int, itemid: String, content: String, parentId: Int, replyToUserId: Int?, replyToUserName: String?) {
        updateState(currentState().copy(isSendingComment = true))
        
        // 直接调用repository的sendReply方法，传递所有必要参数
        repository.sendReply(datatype, itemid, content, parentId, replyToUserId, replyToUserName).collect { result ->
            when (result) {
                is NetworkResult.Loading -> {
                    // 已经设置了发送状态，这里不需要额外处理
                }
                is NetworkResult.Success -> {
                    // 回复发送成功
                    updateState(currentState().copy(isSendingComment = false))
                    sendEvent(SingleEvent.ShowToast(result.data.msg))
                    
                    // 添加新回复到列表
                    result.data.data?.let { addNewComment(it) }
                }
                is NetworkResult.Error -> {
                    updateState(currentState().copy(
                        isSendingComment = false,
                        error = result.exception.message ?: "回复发送失败"
                    ))
                    sendEvent(SingleEvent.ShowToast("回复发送失败: ${result.exception.message}"))
                }
            }
        }
    }
    
    private suspend fun likeComment(commentId: Int) {
        repository.likeComment(commentId).collect { result ->
            when (result) {
                is NetworkResult.Loading -> {
                    // 加载中状态，不需要特殊处理
                }
                is NetworkResult.Success -> {
                    sendEvent(SingleEvent.ShowToast(result.data.msg))
                    
                    // 更新本地评论状态
                    result.data.data?.let { updatedComment ->
                        val updatedComments = currentState().comments.map { comment ->
                            if (comment.id == commentId) {
                                updatedComment
                            } else {
                                comment
                            }
                        }
                        updateState(currentState().copy(comments = updatedComments))
                    }
                }
                is NetworkResult.Error -> {
                    sendEvent(SingleEvent.ShowToast("点赞操作失败: ${result.exception.message}"))
                }
            }
        }
    }
    
    private fun showReward() {
        sendEvent(SingleEvent.ShowToast("显示打赏"))
    }
    
    fun updateDuration(duration: Long) {
        updateState(currentState().copy(duration = duration))
    }
    
    /**
     * 添加新评论到列表顶部
     */
    fun addNewComment(comment: CommentEntityItem) {
        val currentComments = currentState().comments.toMutableList()
        if (comment.parentId == null) {
            // 主评论添加到顶部
            currentComments.add(0, comment)
        } else {
            // 回复评论需要找到父评论并添加到其回复列表
            val parentIndex = currentComments.indexOfFirst { it.id == comment.parentId }
            if (parentIndex != -1) {
                val parentComment = currentComments[parentIndex]
                parentComment.addReply(comment)
                currentComments[parentIndex] = parentComment
            }
        }
        
        // 重新排序并更新状态
        val sortedComments = CommentUtils.sortComments(currentComments, CommentSortType.TIME_DESC)
        updateState(currentState().copy(comments = sortedComments))
    }
}